/*
 * @Description:
 * @Version: 2.0
 * @Autor: snzo.chen
 * @Date: 2023-11-17 08:50:19
 * @LastEditors: snzo.chen
 * @LastEditTime: 2023-11-17 08:52:37
 */
import { Router } from 'vue-router';
import { WhiteNameList, LOGIN_NAME } from './constant';
import Storage from '@/utils/Storage';
import { IS_LOGGED_IN } from '@/enums/cacheEnum';

export function createRouterGuards(router: Router, whiteNameList: WhiteNameList) {
  router.beforeEach(async (to, _, next) => {
    const isLoggedIn = Storage.get(IS_LOGGED_IN, null);
    if (isLoggedIn) {
      if (to.name === LOGIN_NAME) {
        next({ path: '/' });
      } else {
        const hasRoute = router.hasRoute(to.name!);
        if (!hasRoute) {
          // 如果该路由不存在，可能是动态注册的路由，它还没准备好，需要再重定向一次到该路由
          next({ ...to, replace: true });
        } else {
          next();
        }
      }
    } else {
      // no login
      if (whiteNameList.some((n) => n === to.name)) {
        // 免登陆名单 直接进入
        next();
      } else {
        next({
          name: LOGIN_NAME,
          query: { redirect: to.fullPath },
          replace: true,
        });
      }
    }
  });
}
